<?php


namespace app\article\controller;


use app\AdminRest;
use app\article\model\ArticleConfigModel;
use app\card\model\Config;
use app\card\model\UserInfo;
use think\App;


class AdminArticleConfig extends AdminRest
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    public function updateOne()
    {
        $uniacid = $this->_uniacid ?? $this->_param['uniacid'] ?? null;
        if (!$uniacid)
        {
            return $this->error('uniacid is required');
        }
        $input = $this->_input;
        $model = new ArticleConfigModel();
        $data = $model->updateByfilter(['uniacid' => $uniacid], $input);

        if (!$data) {
            $input['uniacid'] = $uniacid;
            unset($input['mini_url']);
            $model->createOne($input);
        }
        $data = longbingGetArticleConfig($uniacid ,true);
        return $this->success($data);
    }


    public function getOne()
    {
        global $_W;

        $uniacid = $this->_uniacid ?? $this->_param['uniacid'] ?? null;
        if (!$uniacid)
        {
            return $this->error('uniacid is required');
        }
//      $model = new ArticleConfigModel();
//      $data = $model->getOne(['uniacid' => $uniacid]);
        $data = longbingGetArticleConfig($uniacid);

        $model_name = config('app.AdminModelList')['app_model_name'];

        $data['mini_url'] = 'https://' . $_SERVER['HTTP_HOST'] . "/index.php?s=/article/articleHtml/msg&i={$uniacid}&uniacid={$uniacid}&version=2.0";

        if(longbingIsWeiqin()) {

            $data['mini_url'] = $_W['siteroot'] . "app/index.php?i={$uniacid}&uniacid={$uniacid}&t=0&version=2.0&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=$model_name&s=/article/articleHtml/msg";
        }
        return $this->success($data);
    }

    public function addArticleUseYear()
    {
        $id = $this->_param['id'];
        if (!$id)
        {
            return $this->error('staff_id is required');
        }
        $m_user_info = new UserInfo();

        $user = $m_user_info->where(['id' => $id])->find();
        if (!$user)
        {
            return $this->error('user_info is not exists');
        }

        $cacheKey = 'article_' . $id;
        delCache($cacheKey);

        $m_card_config = new Config();
        $config = $m_card_config->where(['uniacid' => $this->_uniacid])->find();
        if (!$config)
        {
            return $this->error('config is not exists');
        }


        $signature_total = $m_user_info->where([['uniacid', '=', $this->_uniacid]])->sum('signature');
        $signature_total = (int)$signature_total;

        $total = round($config['autograph'] - 80666);
        if (round($config['signature']) >= $total || $signature_total >= $total)
        {
            return $this->error('fail, up to limit');
        }
        $time = time();


        $m_card_config->where(['uniacid' => $this->_uniacid])->update(['update_time' => $time, 'signature' => round($config['signature'] + 1)]);


        $time = time();
        if ($user['autograph'] > 0)
        {
            $end_time = $user['autograph'] - 123456789;
            if ($end_time > $time)
            {
                $end_time = $end_time + (366 * 24 * 60 * 60) + 123456789;
                $end_time = round($end_time);
            } else
                {
                $end_time = $time + (366 * 24 * 60 * 60) + 123456789;
                $end_time = round($end_time);
            }
        } else
            {
            $end_time = $time + (366 * 24 * 60 * 60) + 123456789;
            $end_time = round($end_time);
        }


        $key = 'cache-' . $this->_uniacid . '-config';
        delCache($key);

        $signature = $user['signature'];
        $signature += 1;
        $signature = round($signature);
        $m_user_info->where(['id' => $id])->update(['autograph' => $end_time, 'update_time' => $time, 'signature' => $signature]);

        return $this->success(true);


    }

    /**
     * 需要分配获客文章的员工列表
     * 获客文章分配名额总数量：                  longbing_card_config.autograph - 80666
     * 总的使用数量：                           longbing_card_config.signature
     * 其中某个员工获客文章到期时间计算方式是:    autograph - 123456789
     *
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function staffList()
    {
        $param = $this->_param;
        //获取分页信息
        $page_config = array(
            'page' => 1,
            'page_count' => 20
        );
        //设置页码
        if (isset($param['page']) && $param['page'] > 0) $page_config['page'] = $param['page'];
        //设置每页的数据
        if (isset($param['page_count']) && $param['page_count'] > 0) $page_config['page_count'] = $param['page_count'];
        $filter = [
            ['s.uniacid', '=', $this->_uniacid],
            ['s.is_staff', '=', 1]
        ];

        if (isset($param['nameForSearch']))
        {
            $filter[] = ['s.name', 'like', '%' . $param['nameForSearch'] . '%'];
        }

        if (isset($param['nickNameForSearch']))
        {
            $filter[] = ['u.nickName', 'like', '%' . $param['nickNameForSearch'] . '%'];
        }

        $m = new UserInfo();

        $page_config['total'] = $m->alias('s')
            ->leftJoin('longbing_card_user u', 'u.id = s.fans_id')
            ->where($filter)
            ->count();

        $staffs = $m->alias('s')
            ->leftJoin('longbing_card_user u', 'u.id = s.fans_id')
            ->where($filter)
            ->field(['s.id', 's.name', 's.avatar', 's.autograph', 'u.nickName'])
            ->page($page_config['page'], $page_config['page_count'])
            ->order('autograph', 'desc')
            ->select()->toArray();


        $staffs = transImagesOne($staffs, ['avatar']);


        foreach ($staffs as $index => $item) {
            $end_time = 0;
            if ($item['autograph'])
            {
                $tmp = $item['autograph'];
                $tmp = $tmp - 123456789;
                $tmp = sprintf("%.0f", $tmp);
                if ($tmp)
                {
                    $end_time = date('Y-m-d H:i:s', $tmp);
                }
            }
            $staffs[$index]['end_time'] = $end_time;
        }

        $page_config['total_page'] = (int)($page_config['total'] / $page_config['page_count']);
        if (($page_config['total'] % $page_config['page_count']) > 0) $page_config['total_page'] = $page_config['total_page'] + 1;
        //设置返回参数
        $result = $page_config;
        //返回数据
        $result['data'] = $staffs;


        $m_card_config = new Config();
        $config = $m_card_config->where(['uniacid' => $this->_uniacid])->find();
        if (!$config)
        {
            return $this->error('config is not exists');
        }

        $total = round($config['autograph'] - 80666);
        $result['total_year'] = $total ?? 0;
        $result['used_year'] = $config['signature'];

        return $this->success($result);
    }
}